//
//  VerificationVC.m
//  DataStatistics
//
//  Created by Kang on 16/3/10.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "VerificationVC.h"
#import <SMS_SDK/SMSSDK.h>
#import "LoginViewModel.h"
#import "GUAAlertView.h"

@interface VerificationVC () <UITextFieldDelegate, UIAlertViewDelegate,UIGestureRecognizerDelegate> {
    
    BOOL isClick;
    CGRect frameDefault;
    IBOutlet NSLayoutConstraint* V_nextView_H;
    NSInteger i;
}


@property (strong, nonatomic) UIToolbar  * VVCtoolbar;
@property (strong, nonatomic) UIButton   * VVCbuton;
@property (strong, nonatomic) UIBarButtonItem   * item;

@property (strong, nonatomic) IBOutlet NSLayoutConstraint* V_verCode;
@property (strong, nonatomic) IBOutlet UILabel* timeLabel;
@property (strong, nonatomic) IBOutlet UIView *vv_NextView;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *V_netxtView;
//计时
@property (nonatomic, strong) NSTimer* timer;
@property (nonatomic, strong) NSTimer* timer2;
@end

// 计时初始值
static int timerCount = 0;
@implementation VerificationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self updateUI];
    i=0;
    
    

    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    
    if (SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
        V_nextView_H.constant = 35;
        //__H_next_Y.constant -= 5;
        if (SCREEN_HEIGHT == 480) {
            _V_verCode.constant += 9;
            
        }
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT,@"667.0")){
        
        V_nextView_H.constant = 40;
        
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"812.0")){
        
        self.V_netxtView.constant = -35;
        
    }
    
    
    
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //self.nextBtn.userInteractionEnabled = NO;
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [_timer invalidate];
    [_timer2 invalidate];
}


- (void)updateUI {
    
    frameDefault = self.view.frame;
    self.title = NSLocalizedString(@"VvcLead_title", nil);
    [self VerificationText];
    [self.nextBtn setTitle:NSLocalizedString(@"next", nil) forState:UIControlStateNormal];
    self.nextBtn.userInteractionEnabled = NO;
    self.vv_NextView.backgroundColor = RGB(26, 32, 40, 1);
    self.view.backgroundColor = RGB(33, 38, 44, 1);
    [self.nextBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    
    [self.view addGestureRecognizer:[UtilToolsClss obtainTapGestureRecognizerObjectWithAction:@selector(VVCkeyboardHide:) withTarget:self]];
    
    
    self.againGetSMSBtn.hidden = YES;
    
    [self.againGetSMSBtn setTintColor:RGB(253, 135, 59, 1)];
    
    
    
    
    _textContent.text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"VvcLead_1", @"我们已经发了一个验证码给您的手机！")];
    self.textContent.font = [UIFont systemFontOfSize:15.f];
    self.iPhonelabel.font = [UIFont systemFontOfSize:15.f];
    
    [self Dtimer];
}


-(void)Dtimer
{
    
    [_timer invalidate];
    _timer = nil;
    [_timer2 invalidate];
    _timer2 = nil;
    
    timerCount = 0;
    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(showRepeatButton) userInfo:nil repeats:YES]; //60
    
    self.timeLabel.textColor = [UIColor lightGrayColor];
    NSTimer* timer2 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES]; // 1
    
    _timer = timer;
    _timer2 = timer2;
    
    NSString *str1 = [NSString stringWithFormat:@"+%@ %@", _VVC_areaNam, _VVC_phoneNumber];
    NSMutableAttributedString *promptLanguageMut1 = [[NSMutableAttributedString alloc]initWithString:str1];
    [promptLanguageMut1 addAttribute:NSForegroundColorAttributeName value:RGB(253, 135, 59, 1) range:NSMakeRange(0, str1.length)];//15
    
    self.iPhonelabel.attributedText =promptLanguageMut1;
    
    _timeLabel.textAlignment = NSTextAlignmentCenter;
    _timeLabel.text = NSLocalizedString(@"VvcLead_0", @"接受短信大约需要60秒。");
    
    i=0;
}



/** 更新计时时间*/
- (void)updateTime {
    timerCount++;
    if (timerCount >= 60) { //60
        [_timer2 invalidate];
        return;
    }
    NSString *second;
    (timerCount == 60) ? ( second = @"VvcSecond") : (second = @"VvcSeconds");
    
    NSString *timestr = [NSString stringWithFormat:@"%@%i%@", NSLocalizedString(@"VvcLead_4", nil), 60-timerCount, NSLocalizedString(second, nil)]; //60
    
    NSMutableAttributedString *promptLanguageMut = [[NSMutableAttributedString alloc]initWithString:timestr];
    // 设置 上面标题
    [promptLanguageMut addAttribute:NSForegroundColorAttributeName value:RGB(253, 135, 59, 1) range:NSMakeRange(10, 2)];
    
    self.timeLabel.attributedText = promptLanguageMut;
    
    if (timerCount == 30) { //30
        if (self.timeLabel.hidden) {
            _timeLabel.hidden = NO;
        }
    }
}

- (void)showRepeatButton {
    self.timeLabel.hidden = YES;
    self.againGetSMSBtn.hidden = NO;
    [_timer invalidate];
    return;
}


// 输入框内容监控
- (void)textLengthMethod:(UITextField*)textField {
    
    // 限制长度
    if (textField == self.VerificationText) {
        if (textField.text.length >  4) {
            textField.text = [textField.text substringToIndex:4];
        }
    }
    
    if (textField.text.length >= 4) {
        self.nextBtn.userInteractionEnabled = YES;
        [self.nextBtn setTitleColor:RGB(253, 135, 59, 1) forState:UIControlStateNormal];
        self.VVCbuton.userInteractionEnabled = YES;
        [self.VVCbuton setTitleColor:RGB(253, 135, 59, 1) forState:UIControlStateNormal];
    }
    else {
        self.nextBtn.userInteractionEnabled = NO;
        [self.nextBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        self.VVCbuton.userInteractionEnabled = NO;
        [self.VVCbuton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
    
}

//清空输入框时调用的方法
-(BOOL)textFieldShouldClear:(UITextField *)textField
{
    NSString *str = self.VerificationText.text;
    if (str.length >0) {
        self.nextBtn.userInteractionEnabled = NO;
        [self.nextBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        self.VVCbuton.userInteractionEnabled = NO;
        [self.VVCbuton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    }
    
    return YES;
}


// 隐藏
- (void)resignRespondersForText {
    if (isClick) {
        isClick = NO;
        if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"480.0")) {
            CABasicAnimation *basicAnim = [CABasicAnimation animationWithKeyPath:@"bounds"];
            basicAnim.toValue = [NSValue valueWithCGRect:CGRectMake(self.view.frame.origin.x, 64, self.view.frame.size.width, self.view.frame.size.height)];
            [self.view.layer addAnimation:basicAnim forKey:@"viewBasicAnim"];
            
            [_VerificationText resignFirstResponder];
        }
        else {
            [_VerificationText resignFirstResponder];
            [self.view endEditing:YES];
        }
        
    }
}

- (void)textFieldDidBeginEditing:(UITextField*)textField
{
    if (!isClick) {
        isClick = YES;
        [self.VerificationText becomeFirstResponder];
    }
    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"480.0")) {
        CGRect newFrome = self.view.frame;
        newFrome.origin.y = 40;
        [UIView animateWithDuration:0.24 animations:^{
            [self.view setFrame:newFrome];
        }];
    }
}


// 手势方法键盘隐藏
- (void)VVCkeyboardHide:(UITapGestureRecognizer*)tap
{
    [self resignRespondersForText];
}


#pragma mark - 校验短信 请求
- (IBAction)verificationNext:(id)sender {

    // 校验手机短信
    NSDictionary *dic = @{@"loginName":_VVC_phoneNumber,
                          @"zone":_VVC_areaNam,
                          @"code":_VerificationText.text};
    

    NSLog(@"字典 ========  %@",dic);
    
    [LoginViewModel requestWithUrlForVerification:self andParam:dic success:^(id model) {
        // 验证通过后跳转
        [_timer invalidate];
        [_timer2 invalidate];
        _againGetSMSBtn.hidden = NO;
        _timeLabel.hidden = YES;
        
        // 下一页返回的字样
        UIBarButtonItem* backIetm = [[UIBarButtonItem alloc] init];
        backIetm.title = NSLocalizedString(@"back", nil);
        self.navigationItem.backBarButtonItem = backIetm;
        
        if ([_VVCsignStr isEqualToString:@"Forget"]) {
            [self performSegueWithIdentifier:@"gotoForget" sender:self];
            [self resignRespondersForText];
            
        }else if ([_VVCsignStr isEqualToString:@"Registered"]) {
            [self performSegueWithIdentifier:@"gotoSubmitVC" sender:self];
            [self resignRespondersForText];
            
        }
        
    } failure:^(NSString *err) {
        i++;
        if (i<=3) {
            [MBProgressHUD yty_showErrorWithTitle:nil detailsText:err toView:self.view];
            
        }else if (i>3) {
            [MBProgressHUD yty_showErrorWithTitle:nil detailsText:@"当前验证码超过有效次数，请重新获取！" toView:self.view];
            [self.againGetSMSBtn setTitle:@"请重新获取验证码" forState:UIControlStateNormal];
            self.timeLabel.hidden = YES;
            self.againGetSMSBtn.hidden = NO;
            [_timer2 invalidate];
            [_timer invalidate];
            return;
        }
    }];
}


// 传值
- (void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender {
    if ([_VVCsignStr isEqualToString:@"Forget"]) {
        if ([segue.identifier compare:@"gotoForget"] == NO) {
            id vc = segue.destinationViewController;
            [vc setValue:_VVCsignStr forKey:@"FPVCsignStr"];
            [vc setValue:_VVC_areaNam forKey:@"FPVC_areaNam"];
            [vc setValue:_VVC_phoneNumber forKey:@"FPVC_phoneNumber"];
            [vc setValue:self.VerificationText.text forKey:@"FPVC_SMSCode"];
        }
    }
    else if ([_VVCsignStr isEqualToString:@"Registered"]) {
        if ([segue.identifier compare:@"gotoSubmitVC"] == NO) {
            id vc = segue.destinationViewController;
            [vc setValue:_VVCsignStr forKey:@"SVCsignStr"];
            [vc setValue:_VVC_areaNam forKey:@"SVC_areaNam"];
            [vc setValue:_VVC_phoneNumber forKey:@"SVC_phoneNumber"];
            [vc setValue:self.VerificationText.text forKey:@"SVC_SMSCode"];
        }
    }
}


- (IBAction)againGetSMS:(UIButton*)sender {
    
    //[self.view endEditing:YES];
    

    __weak VerificationVC* verifyVC = self;
    verifyVC.VerificationText.clearButtonMode = UITextFieldViewModeNever;
    
    
    NSString* str = [NSString stringWithFormat:@"%@:+%@    %@", NSLocalizedString(@"VvcLead_5", nil), _VVC_areaNam, _VVC_phoneNumber];
    
    
    GUAAlertView *v = [GUAAlertView alertViewWithTitle:@"请确认手机号码"
                                               message:str                                       buttonTitle:@"发送"
                                   buttonTouchedAction:^{
                                       NSLog(@"button touched");
                                       
                                       NSString* str2 = [_VVC_areaNam stringByReplacingOccurrencesOfString:@"+" withString:@""];
                                       
                                       [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:_VVC_phoneNumber zone:str2 customIdentifier:nil result:^(NSError* error) {
                                           
                                           self.timeLabel.hidden = NO;
                                           self.againGetSMSBtn.hidden = YES;
                                           [self Dtimer];
                                           
                                           
                                           if (!error) {
                                               NSLog(@"获取验证码成功");
                                               
                                               [MBProgressHUD showSuccess:NSLocalizedString(@"send", nil) toView:self.view];
                                               [self.VVC_window.rootViewController dismissViewControllerAnimated:YES completion:^{
                                                   
                                                   verifyVC.againGetSMSBtn.hidden = YES;
                                                   verifyVC.timeLabel.hidden = NO;
                                                   verifyVC.timeLabel.text = NSLocalizedString(@"VvcLead_0", nil);
                                                   
                                                   [verifyVC.timer invalidate];
                                                   [verifyVC.timer2 invalidate];
                                                   
                                                   timerCount = 0;
                                                   NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(showRepeatButton) userInfo:nil repeats:YES]; //60
                                                   
                                                   verifyVC.timeLabel.textColor = [UIColor lightGrayColor];
                                                   NSTimer* timer2 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES]; // 1
                                                   
                                                   verifyVC.timer = timer;
                                                   verifyVC.timer2 = timer2;
                                                   [verifyVC.VerificationText becomeFirstResponder];
                                                   
                                               }];
                                           }
                                           else {

                                               NSString *messageStr = [NSString stringWithFormat:@"%zidescription",error.code];
                                               [MBProgressHUD yty_showErrorWithTitle:NSLocalizedString(@"codesenderrtitle", nil) detailsText:NSLocalizedString(messageStr, nil) toView:self.view];
                                           }
                                           
                                       }];
                                       
                                       
                                       
                                       
                                       
                                   } dismissAction:^{
                                       NSLog(@"dismiss");
                                       
                                   }];
    [v show];
    
    
    
    
}

#pragma get / set

//VerificationText
- (UITextField *)VerificationText {
    if (!_VerificationText) {
    }
    [UITextField addYTYanKTextFielStyle1:_VerificationText withString:NSLocalizedString(@"VvcLead_2", @"请输入验证码")];
    _VerificationText.clearButtonMode = UITextFieldViewModeUnlessEditing;
    _VerificationText.delegate = self;
    [_VerificationText addTarget:self action:@selector(textLengthMethod:) forControlEvents:UIControlEventEditingChanged];
    [_VerificationText setInputAccessoryView:self.VVCtoolbar];
    return _VerificationText;
}

- (UIToolbar *)VVCtoolbar {
    if (!_VVCtoolbar) {
        
        if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"480.0")) {

            _VVCtoolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 35)];
            [_VVCtoolbar setBackgroundImage:[UIImage imageNamed:@"bottom-bg"] forToolbarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
            [_VVCtoolbar addSubview:self.VVCbuton];
            

        
        }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
            _VVCtoolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 35)];
            [_VVCtoolbar setBackgroundImage:[UIImage imageNamed:@"bottom-bg"] forToolbarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
            [_VVCtoolbar addSubview:self.VVCbuton];
            
            
        }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT,@"667.0")) {
            _VVCtoolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
            [_VVCtoolbar setBackgroundImage:[UIImage imageNamed:@"bottom-bg"] forToolbarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
            [_VVCtoolbar addSubview:self.VVCbuton];
            
            
            
        }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT,@"736.0")) {
            
            _VVCtoolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
            [_VVCtoolbar setBackgroundImage:[UIImage imageNamed:@"bottom-bg"] forToolbarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
            [_VVCtoolbar addSubview:self.VVCbuton];
        }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"812.0")){
            
            _VVCtoolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 46)];
            [_VVCtoolbar setBackgroundImage:[UIImage imageNamed:@"bottom-bg"] forToolbarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
            [_VVCtoolbar addSubview:self.VVCbuton];
            
        }
        
    }
    return _VVCtoolbar;
}

- (UIButton *)VVCbuton {
    if (!_VVCbuton) {
        
        if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"480.0")) {

            _VVCbuton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 38 - 29, 0, 50, 35)];
            _VVCbuton.titleLabel.font = [UIFont boldSystemFontOfSize:16.f];
            [_VVCbuton setTitle:NSLocalizedString(@"next", @"下一页") forState:UIControlStateNormal];
            [_VVCbuton addTarget:self action:@selector(verificationNext:) forControlEvents:UIControlEventTouchDown];
            [_VVCbuton setUserInteractionEnabled:NO];
            [_VVCbuton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];

        }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
            _VVCbuton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 38 - 29, 0, 50, 35)];
            _VVCbuton.titleLabel.font = [UIFont boldSystemFontOfSize:16.f];
            [_VVCbuton setTitle:NSLocalizedString(@"next", @"下一页") forState:UIControlStateNormal];
            [_VVCbuton addTarget:self action:@selector(verificationNext:) forControlEvents:UIControlEventTouchDown];
            [_VVCbuton setUserInteractionEnabled:NO];
            [_VVCbuton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            
        }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT,@"667.0")) {
            _VVCbuton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 38 - 30, 0, 50, 40)];
            _VVCbuton.titleLabel.font = [UIFont boldSystemFontOfSize:16.f];
            [_VVCbuton setTitle:NSLocalizedString(@"next", @"下一页") forState:UIControlStateNormal];
            [_VVCbuton addTarget:self action:@selector(verificationNext:) forControlEvents:UIControlEventTouchDown];
            [_VVCbuton setUserInteractionEnabled:NO];
            [_VVCbuton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            
            
        }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT,@"736.0")) {
            
            _VVCbuton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 38 - 31, 0, 50, 44)];
            _VVCbuton.titleLabel.font = [UIFont boldSystemFontOfSize:16.f];
            [_VVCbuton setTitle:NSLocalizedString(@"next", @"下一页") forState:UIControlStateNormal];
            [_VVCbuton addTarget:self action:@selector(verificationNext:) forControlEvents:UIControlEventTouchDown];
            [_VVCbuton setUserInteractionEnabled:NO];
            [_VVCbuton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            
        }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"812.0")){
            
            _VVCbuton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 38 - 32, 0, 50, 44)];
            _VVCbuton.titleLabel.font = [UIFont boldSystemFontOfSize:16.f];
            [_VVCbuton setTitle:NSLocalizedString(@"next", @"下一页") forState:UIControlStateNormal];
            [_VVCbuton addTarget:self action:@selector(verificationNext:) forControlEvents:UIControlEventTouchDown];
            [_VVCbuton setUserInteractionEnabled:NO];
            [_VVCbuton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            
        }
        
        self.item = [[UIBarButtonItem alloc] initWithCustomView:self.VVCbuton];
        UIBarButtonItem *flexibleitem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemFlexibleSpace) target:self action:nil];
        NSArray *items = @[flexibleitem,flexibleitem,_item];
        [self.VVCtoolbar setItems:items animated:YES];
        
    }
    return _VVCbuton;
}



@end

